/*
 * @Author: xiaoyan
 * @Date: 2021-09-10 11:09:16
 * @LastEditors: xiaoyan
 * @LastEditTime: 2022-01-26 17:41:18
 * @Description: 请求文件配置
 * @FilePath: \user_auth_front\src\utils\request.ts
 */
import axios, { AxiosRequestConfig, AxiosRequestHeaders } from 'axios'
import { message } from 'antd';
import { removeToken} from "@/store/modules/user"
import { getToken,removeToken as delToken} from '@/utils/storage'
import store from "@/store"

// create an axios instance
const service = axios.create({
  baseURL: '', // api 的 base_url
  timeout: 50000 // request timeout
})
// request interceptor
service.interceptors.request.use(
  (config:AxiosRequestConfig) => {
    // Do something before request is sent
    const token =  store.getState().user.token;
    if (token) {
      // 让每个请求携带token-- ['auth']为自定义key 请根据实际情况自行修改
      const headers:AxiosRequestHeaders = config.headers || {};
      headers['auth'] = getToken();
    }
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => response.data,
  
  error => {
    if(error.response){
      switch (error.response.status) {
        case 401:
        case 403: {
          delToken();
          store.dispatch(removeToken());
          break;
        }
      }
    }else{
        message.error(errTip(error.message));
    }
    return Promise.reject(error)
  }
)

function errTip(msg:string){
  if(msg.indexOf("timeout") != -1){
    return "请求超时！";
  }else if(msg.indexOf("Network Error") != -1){
    return "无法连接网络！";
  }else{
    return msg;
  }
}
export  {service as request }